<?php

namespace app\admin\controller\card;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Db;
use com\TPWechat;
use app\admin\model\StoreCancel as CancelModel;
use app\admin\model\HkStore;

/**
 * 店铺核销员
 *
 * @icon fa fa-circle-o
 */
class Storecancel extends Backend
{
    
    /**
     * StoreCancel模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $storeModel = new HkStore();
        $this->view->assign('storeList',$storeModel->storeList());
        $this->model = model('StoreCancel');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('store')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('store')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    //扫码完成后跳转
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                /*
                 * 已经弃用,如果为了兼容老版可取消注释
                  foreach ($params as $k => &$v)
                  {
                  $v = is_array($v) ? implode(',', $v) : $v;
                  }
                 */
                if ($this->dataLimit)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 应用数据限制
                if ($this->appletLimit)
                {
                    $params['appletid'] = $this->appletLimit;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    if(Db::table('uct_store_cancel')->where(['openid'=>$params['openid']])->find()){
                        $this->error('此核销员已经存在');
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success('待确认，请等待',url('card/storecancel/index'),['ref' => 'addtabs']);
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $code = input('code');
        if(!$code){  //若用户禁止授权，或者恶意访问
            $this->redirect('admin/index/index');
        }
        $appletid = input('appletid');
        $appinfo = model('wechat_applet')->where('appletid',$appletid)->find();
        $options['token'] = $appinfo['token'];
        $options['appid'] = $appinfo['appid'];    //初始化options信息
        $options['appsecret'] = $appinfo['appsecret'];
        $options['encodingaeskey'] = $appinfo['aeskey'];
        $options['debug'] = config('app_debug');            //调试状态跟随系统调试状态
        if($options['debug']){
            $options['logcallback'] = 'trace';              //微信类调试信息用trace方法记录到TP日志文件中
        }
        $weObj = new TPWechat($options);
        $result = $weObj->getOauthAccessToken();
        if(!$result) { //code码乱来
            $this->redirect('admin/index/index');
        }
        //判断是否已经添加过了
        $user = CancelModel::get(['openid' => $result['openid']]);
        if($user){ //存在核销员,顺便更新数据
            $this->error('核销员已存在');
        }
        $info = $weObj->getOauthUserinfo($result['access_token'],$result['openid']);
        $this->view->assign('info',$info);
        return $this->view->fetch();
    }

     //显示登陆二维码
     public function qrcode()
     {
         //扫码应用的条件
         $map['admin_id'] = 1;
         $map['business_info'] = '{"wxlogin":1}';  //TODO:支持多个配置参数选出wxlogin配置项的查找
         $appinfo = model ( 'wechat_applet' )->where ( $map )->find ();
         $redirect_uri = httpTohttps(url('add',['appletid' => $appinfo['appletid']],false,true));
         $state = time();
         $this->assign('appid', $appinfo['appid']);
         $this->assign('redirect_uri', urlencode($redirect_uri));
         $this->assign('state', $state);
         return $this->view->fetch();
     }
}
